import logging
import imaplib

from pymomail.lib.base import *
from pymomail.lib.mailstore import *

log = logging.getLogger(__name__)

class MessageController(BaseController):
    _M = None

    def __init__(self):
        self._M = MailStoreFactory(config['imap_url'])

    def _do_login(self):
        self._M.login(''.join([session['username'], session['domain']]), session['password'])

    def _require_login(self):
        response.headers['Content-type'] = 'text/vnd.wap.wml'
            try:
                self._do_login()
            except KeyError:
                return redirect_to(url_for('login'))
            except:
                return render('/wml/403.mako')
                
    def view(self, fname, uid):
        self._require_login()
        c.message = self._M.message(fname, uid)
        ret = render('/wml/message.mako')
        self._M.logout()
        return ret

    def headers(self, fname, uid):
        print "headers for %s, %s" % ( fname, uid)
        self._require_login()
        c.message = self._M.message(fname, uid)
        ret = render('/wml/headers.mako')
        self._M.logout()
        return ret

    def source(self, fname, uid):
        self._require_login()
        c.message = self._M.message(fname, uid)
        ret = render('/wml/source.mako')
        self._M.logout()
        return ret

